package com.huluobo.a2205kotlinjetpackdemo.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.google.gson.Gson
import com.huluobo.a2205kotlinjetpackdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create

class RetrofitActivity : AppCompatActivity() {
    private val retrofit = Retrofit.Builder().baseUrl("http://10.161.9.80:7012")
        .addConverterFactory(GsonConverterFactory.create()).build()

    private val apiService = retrofit.create(ApiService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_retrofit)

//        apiService.loadBanner().enqueue(object : Callback<BannerBeanResult> {
//            //成功的返回
//            override fun onResponse(call: Call<BannerBeanResult>, response: Response<BannerBeanResult>) {
//                val json = Gson().toJson(response.body())
//                val bean = Gson().fromJson(json, BannerBeanResult::class.java)
//                val tv = findViewById<TextView>(R.id.retrofit_tv)
//                tv.text = bean.toString()
//            }
//
//            //失败的返回
//            override fun onFailure(call: Call<BannerBeanResult>, e: Throwable) {
//            }
//        })
        val job = Job()
        CoroutineScope(job).launch(Dispatchers.Main) {
            val result = apiService.loadBanner2()
            val tv = findViewById<TextView>(R.id.retrofit_tv)
            tv.text = result.toString()
        }

        //retrofit2.8一下的,不支持主线程调用协程,需要切换
//        CoroutineScope(job).launch (Dispatchers.Main){
//            val result = withContext(Dispatchers.IO){
//                apiService.loadBanner2()
//            }
//            val tv = findViewById<TextView>(R.id.retrofit_tv)
//            tv.text = result.toString()
//        }
    }
}